﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using System.Reflection;

namespace WebAPI.Filter
{
    public class UnitOfWorkFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            await next();
            var des = context.ActionDescriptor as ControllerActionDescriptor;
            if (des != null)
            {
                var workAttr = des.ControllerTypeInfo.GetCustomAttribute<UnitOfWorkAttribute>();
                workAttr = workAttr ?? des.MethodInfo.GetCustomAttribute<UnitOfWorkAttribute>();
                if (workAttr != null)
                {
                    foreach (var dbCtxType in workAttr.DbContextTypes)
                    {
                        var dbContext = context.HttpContext.RequestServices.GetRequiredService(dbCtxType) as DbContext;
                        if (dbContext != null) await dbContext.SaveChangesAsync();
                    }
                }
            }
        }
    }
}
